import {
  Table,
  Card,
  Button,
  ConfigProvider,
  Image,
  Form,
  Input,
  Select,
  Modal,
  DatePicker,
  Upload,
  message,
  Space,
  notification,
  Dropdown,
  Collapse,
  Row,
  Col,
  Tag,
} from 'antd';
import { UploadOutlined, ExclamationCircleOutlined } from '@ant-design/icons';
import React, { useState, useEffect } from 'react';
import { useRequest, connect } from 'umi';
import type { Dispatch } from 'umi';
import moment from 'moment';
import zhCN from 'antd/lib/locale/zh_CN';
import DownloadExcel from '@/utils/DownloadExcel.js';

const { Option } = Select;
const { Panel } = Collapse;
const { confirm } = Modal;

// 空白信息请补充完整，新增项目提供任务书或计划书红章扫描件，以“序号+项目名称+负责人”命名
const TbaleToNameMap: Map = {
  REWARD: '奖励',
  INVITATION_REPORT: '特邀报告',
  LAB_STAFF_REPORT: '会议报告',
  PAPER: '论文',
  TALENT_TITLE: '人才称号',
  PATENT: '申请专利',
  HORIZONTAL_PROJECT: '横向项目',
  BOOK_PUBLISH: '专著',
  STANDARD: '标准',
  CO_CULTURE_STU: '联合培养学生情况',
  GOOD_STU: '优博优硕',
  ACHIEVE_TRANS: '成果转化',
  VERTICAL_PROJECT: '纵向项目',
  VISIT_SCHOLAR: '访问学者',
  SOCIAL_SERVICE: '社会化服务',
  HOST_MEETING: '主办承办会议',
  INTERNATIONAL_MEETING: '国际会议',
  CULTIVATE_STU: '培养硕博学生数',
  GRANT_PATENT: '授权专利',
  OTHER_ACHIEVEMENTS: '其他标志性成果',
};
//STANDARD表  AUTHOR字段  单人
const ManyPeople: Map = {
  PAPER: 'AUTHOR',
  BOOK_PUBLISH: 'AUTHOR',
  REWARD: 'DIRECTOR',
  GRANT_PATENT: 'TEAM',
  PATENT: 'TEAM',
};
const TableBuileder = (props: any) => {
  const { DataList, dataLoad, dispatch, tableKey, OptMap, CJXMap } = props;
  const [form] = Form.useForm();
  const [searchform] = Form.useForm();
  const [isModalVisible, setIsModalVisible] = useState(false);
  //审批 请求
  const userApprove = useRequest(
    (data = {}) => {
      return {
        url: 'http://10.1.40.84:9993/userApprove',
        method: 'POST',
        headers: {
          Authorization: localStorage.getItem('token') || '',
        },
        data,
      };
    },
    {
      onSuccess: (result, params) => {
        console.log(result);
      },
      onError: (e, params) => {
        console.log(e);
        console.log(params);
      },
      manual: true,
    },
  );
  function showConfirm(record: any) {
    confirm({
      title: '确认通过此次审批吗？',
      icon: <ExclamationCircleOutlined />,
      content: '请检查材料是否与情况相符！',
      onOk() {
        userApprove
          .run({
            tableName: tableKey,
            update: {
              ID: record.ID,
              IS_PASS: '2',
            },
          })
          .then(() => {
            dispatch({
              type: 'labmanagement/dataSearch',
              payload: { tableName: tableKey },
            });
          });
      },
      onCancel() {
        userApprove
          .run({
            tableName: tableKey,
            update: {
              ID: record.ID,
              IS_PASS: '3',
            },
          })
          .then(() => {
            dispatch({
              type: 'labmanagement/dataSearch',
              payload: { tableName: tableKey },
            });
          });
        // console.log(record);
        // message.success("取消审核")
      },
      cancelText: '拒绝',
      okText: '通过',
      closable: true,
    });
  }
  useEffect(() => {
    dispatch({
      type: 'labmanagement/dataSearch',
      payload: { tableName: tableKey },
    });
  }, [tableKey]);
  useEffect(() => {
    dispatch({
      type: 'labmanagement/getOptMap',
    });
    dispatch({
      type: 'labmanagement/dataFindDataCol',
    });
  }, []);
  const tableScrollBuilder = (value: any) => {
    switch (value) {
      case 'PAPER':
        return {
          x: 'calc(1300px + 50%)',
        };
      case 'ACHIEVE_TRANS':
        return {
          x: 'calc(1800px + 50%)',
          y: 480,
        };
      case 'INTERNATIONAL_MEETING':
        return {
          x: 'calc(600px + 50%)',
        };
      case 'LAB_STAFF_REPORT':

      case 'HOST_MEETING':
        return {
          x: 'calc(600px + 80%)',
        };
      case 'INVITATION_REPORT':
      case 'CO_CULTURE_STU':
      case 'VISIT_SCHOLAR':
      case 'TALENT_TITLE':
      case 'GOOD_STU':
        return false;
      default:
        return {
          x: 'calc(1200px + 50%)',
        };
    }
  };
  const InputOrDateOrSelect = (value: any) => {
    if (value.TYPE === 'DatePicker') {
      return <DatePicker allowClear style={{ width: '100%' }} />;
    } else if (value.TYPE === 'Input') {
      return <Input allowClear style={{ width: '100%' }} />;
    } else if (value.TYPE === 'Select') {
      return (
        <Select style={{ width: '100%' }}>
          {value.DEFAULTS.map((element: any, index: any) => {
            return (
              <Option value={element} key={index}>
                {element}{' '}
              </Option>
            );
          })}
        </Select>
      );
    }
  };
  const formItemBuilder = (value: any) => {
    return (
      <>
        <Form.Item
          label={value.TITLE}
          name={value.KEY}
          key={value.KEY}
          hidden={value.KEY === 'ID'}
        >
          {InputOrDateOrSelect(value)}
        </Form.Item>
      </>
    );
    // console.log(ManyPeople[`${tableKey}`] === value.KEY);
  };
  const onSearch = (value: any) => {
    console.log(value);
    let paramTemp: any = [];
    Object.keys(value).map((element: any, index: any) => {
      if (value[`${element}`]) {
        paramTemp.push({
          key: element,
          value: value[`${element}`],
          option: OptMap[`${tableKey}`][`${element}`],
        });
      }
    });
    dispatch({
      type: 'labmanagement/dataSearch',
      payload: {
        tableName: tableKey,
        param: paramTemp,
      },
    }).then(() => {});
  };
  const columBuilderNew = (value: any) => {
    let valueTemp: any = JSON.parse(JSON.stringify(value));
    let valueTempTemp: any = [];
    valueTemp.map((element: any, index: any) => {
      if (
        element?.key === 'APPROVED_FUND' ||
        element?.key === 'SCHOOL_FUND' ||
        element?.key === 'CONTRACT_MONEY' ||
        element?.key === 'REALGET_MONEY' ||
        element?.key === 'TRANS_MONEY'
      ) {
        let objTemp: any = {
          title: element.title,
          dataIndex: element.dataIndex,
          key: element.key,
          align: 'center',
          ellipsis: true,
          render: (text: any) => {
            if (text) {
              return <span>{text}万元</span>;
            } else {
              return null;
            }
          },
        };
        valueTempTemp.push(objTemp);
      }

      switch (element.key) {
        case 'ANNEX_PATH':
          let objTemp: any = {
            title: element.title,
            dataIndex: element.dataIndex,
            key: element.key,
            align: 'center',
            ellipsis: true,
            render: (text: any) => {
              if (text) {
                return (
                  <a
                    onClick={() => {
                      window.open(text);
                    }}
                  >
                    下载
                  </a>
                );
              } else {
                return null;
              }
            },
          };
          valueTempTemp.push(objTemp);
          break;
        case 'PIC_PATH':
          let objpicPath: any = {
            title: element.title,
            dataIndex: element.dataIndex,
            key: element.key,
            align: 'center',
            ellipsis: true,
            render: (value: any) => {
              if (value !== null) {
                return <Image width={200} src={value} />;
              } else {
                return null;
              }
            },
          };
          valueTempTemp.push(objpicPath);
          break;
        case 'IS_PASS':
          let objIsPass: any = {
            title: element.title,
            dataIndex: element.dataIndex,
            key: element.key,
            align: 'center',
            width: 120,
            ellipsis: true,
            sorter: {
              compare: (a: { IS_PASS: string }, b: { IS_PASS: string }) =>
                a.IS_PASS.localeCompare(b.IS_PASS),
              // multiple: 2,
            },
            render: (value: any) => {
              if (value === '0') {
                return <Tag>缺失附件信息</Tag>;
              } else if (value === '1') {
                return <Tag>审核中</Tag>;
              } else if (value === '2') {
                return <Tag>审核通过</Tag>;
              } else if (value === '3') {
                return <Tag>已拒绝</Tag>;
              } else {
                return null;
              }
            },
          };
          valueTempTemp.push(objIsPass);
          break;
        default:
          let elementTemp = JSON.parse(JSON.stringify(element));
          if (elementTemp.key === 'PATENT_NUM') {
            // console.log(elementTemp);
            elementTemp.width = '100px';
          }
          if (elementTemp.key === 'ID') {
            // console.log(elementTemp);
            elementTemp.width = '50px';
          }
          if (
            elementTemp?.key === 'APPROVED_FUND' ||
            elementTemp?.key === 'SCHOOL_FUND' ||
            elementTemp?.key === 'CONTRACT_MONEY' ||
            elementTemp?.key === 'REALGET_MONEY' ||
            elementTemp?.key === 'TRANS_MONEY'
          ) {
            break;
          }
          elementTemp.align = 'center';
          elementTemp.ellipsis = true;
          valueTempTemp.push(elementTemp);
          break;
      }
    });
    valueTempTemp.push({
      title: '操作',
      align: 'center',
      fixed: 'right',
      width: 200,
      render: (value: any, record: any) => {
        return (
          <Space>
            <Upload
              {...uploadProps}
              data={{ table: tableKey, column: 'ANNEX_PATH', id: record.ID }}
            >
              <Button
                type="link"
                size="small"
                disabled={value.CAN_UPDATE === '0'}
              >
                上传附件
              </Button>
            </Upload>
            <Button
              type="link"
              size="small"
              onClick={() => {
                showModal(record);
              }}
              disabled={value.CAN_UPDATE === '0'}
            >
              编辑
            </Button>
            {localStorage.getItem('adminFlag') === '1' ? (
              <Button
                type="link"
                size="small"
                onClick={() => {
                  showConfirm(record);
                }}
                disabled={value.ANNEX_PATH ? false : true}
              >
                审批
              </Button>
            ) : null}
          </Space>
        );
      },
    });
    // valueTemp.concat([])
    // console.log(valueTempTemp);
    return valueTempTemp;
  };
  const onEdit = (value: any) => {
    console.log(value);
  };
  const showModal = (value: any) => {
    form.resetFields();
    console.log(value);
    console.log(CJXMap[`${tableKey}`]);
    let valueTemp: any = JSON.parse(JSON.stringify(value));
    CJXMap[`${tableKey}`]?.map((element: any, index: any) => {
      console.log(value[`${element}`]);
      let elementTemp = new Object();
      if (value[`${element}`]) {
        elementTemp[`${element}`] = moment(value[`${element}`]);
        console.log(elementTemp);
        form.setFieldsValue(elementTemp);
        delete valueTemp[`${element}`];
      }
    });
    console.log(valueTemp);

    form.setFieldsValue(valueTemp);
    setIsModalVisible(true);
  };
  const handleOk = () => {
    form.validateFields().then((value: any) => {
      // console.log(CJXMap[`${tableKey}`]);
      // console.log(value);
      let valueTemp: any = JSON.parse(JSON.stringify(value));
      CJXMap[`${tableKey}`]?.map((element: any, index: any) => {
        valueTemp[`${element}`] = moment(valueTemp[`${element}`]).format(
          'YYYY-MM-DD',
        );
      });
      console.log(valueTemp);

      if (value[`${ManyPeople[`${tableKey}`]}`]) {
        dispatch({
          type: 'labmanagement/matchAuthor',
          payload: {
            payload: { str: value[`${ManyPeople[`${tableKey}`]}`] },
            value: {
              tableName: tableKey,
              update: valueTemp,
            },
            type: 'edit',
          },
        })
          .then(() => {
            dispatch({
              type: 'labmanagement/dataSearch',
              payload: { tableName: tableKey },
            });
          })
          .then(() => {
            setIsModalVisible(false);
          });
      } else {
        dispatch({
          type: 'labmanagement/dataUpdate',
          payload: {
            tableName: tableKey,
            update: valueTemp,
          },
        })
          .then(() => {
            dispatch({
              type: 'labmanagement/dataSearch',
              payload: { tableName: tableKey },
            });
          })
          .then(() => {
            setIsModalVisible(false);
          });
      }
    });
  };
  const handleCancel = () => {
    setIsModalVisible(false);
  };
  //下载文档
  const handleDownloadExcel = () => {
    DownloadExcel(
      DataList?.columns,
      DataList?.dataSource,
      TbaleToNameMap[`${tableKey}`] +
        `信息表${moment().format('YYYYMMDDHHmmss')}`,
      [],
      () => {
        setTimeout(() => {
          notification.success({ message: '导出成功!' });
        }, 300);
      },
    );
  };
  const token = localStorage.getItem('token');
  const uploadProps = {
    name: 'file',
    action: 'http://10.1.40.84:9993/uploadFile',
    headers: {
      // authorization: 'authorization-text',
      Authorization: token ? token : '',
    },
    beforeUpload(file: any) {
      console.log(file.name);
      var arr = file.name.split('-'); //通过 + 字符来将字符串转换成数组
      console.log(arr.length - 1);
      if (arr.length - 1 === 2) {
        return true;
      } else {
        notification.error({ message: '"取名格式错误，请检查"!' });
        return false;
      }
    },
    onChange(info) {
      if (info.file.status !== 'uploading') {
        console.log(info.file, info.fileList);
      }
      if (info.file.status === 'done') {
        dispatch({
          type: 'labmanagement/dataSearch',
          payload: { tableName: tableKey },
        });
        message.success(`${info.file.name} 文件上传成功！！`);
      } else if (info.file.status === 'error') {
        message.error(`${info.file.name} 文件上传失败！！`);
      }
    },
    maxCount: 1,
    showUploadList: false,
  };
  const [isItem, setIsItem] = useState(false);
  const [addModalForm] = Form.useForm();

  const showAddModal = () => {
    setIsItem(true);
  };
  const handleIsItemOk = () => {
    addModalForm.validateFields().then((value: any) => {
      console.log(value);
      console.log(value[`${ManyPeople[`${tableKey}`]}`]);
      if (value[`${ManyPeople[`${tableKey}`]}`]) {
        dispatch({
          type: 'labmanagement/matchAuthor',
          payload: {
            payload: { str: value[`${ManyPeople[`${tableKey}`]}`] },
            value: {
              tableName: tableKey,
              update: value,
            },
            type: 'add',
          },
        }).then(() => {
          dispatch({
            type: 'labmanagement/dataSearch',
            payload: { tableName: tableKey },
          });
        });
      } else {
        dispatch({
          type: 'labmanagement/dataAdd',
          payload: {
            tableName: tableKey,
            update: value,
          },
        }).then(() => {
          dispatch({
            type: 'labmanagement/dataSearch',
            payload: { tableName: tableKey },
          });
        });
      }
    });
    setIsItem(false);
  };
  const handleIsItemCancel = () => {
    setIsItem(false);
  };

  return (
    <ConfigProvider locale={zhCN}>
      <Card
        bordered={false}
        title={
          <Form layout={'inline'} form={searchform} onFinish={onSearch}>
            {DataList?.search?.map((element: any, index: any) => {
              return (
                <>
                  <Form.Item
                    label={element.NAME}
                    name={element.TITLE}
                    key={element.TITLE}
                  >
                    <Input allowClear />
                  </Form.Item>
                </>
              );
            })}
            {DataList?.search?.length !== 0 ? (
              <>
                <Form.Item>
                  <Button type="primary" htmlType="submit">
                    查询
                  </Button>
                </Form.Item>
                <Form.Item>
                  <Button
                    type="primary"
                    onClick={() => {
                      dispatch({
                        type: 'labmanagement/dataSearch',
                        payload: { tableName: tableKey },
                      });
                    }}
                  >
                    重置
                  </Button>
                </Form.Item>
              </>
            ) : null}
          </Form>
        }
        extra={
          <Space>
            <Button type="primary" onClick={showAddModal}>
              添加{`${TbaleToNameMap[tableKey]}`}
            </Button>

            <Button type="primary" onClick={handleDownloadExcel}>
              下载
            </Button>
          </Space>
        }
      >
        <Table
          bordered
          dataSource={DataList?.dataSource}
          // columns={columnsBuilder(DataList?.columns || [])}
          columns={columBuilderNew(DataList?.columns || [])}
          loading={dataLoad}
          scroll={tableScrollBuilder(tableKey)}
          pagination={{ size: 'small' }}
          rowKey={(record) => record.ID}
          key={tableKey}
          size={'small'}
          // scroll={{ x: 'calc(1500px + 50%)' }}
        />
      </Card>
      <Modal
        title="修改信息"
        visible={isModalVisible}
        onOk={handleOk}
        onCancel={handleCancel}
        forceRender
      >
        <Form
          layout={'vertical'}
          form={form}
          onFinish={onEdit}
          // labelCol={{ span: 6 }}
          // wrapperCol={{ span: 14 }}
        >
          {DataList?.edit?.map((element: any, index: any) => {
            return <> {formItemBuilder(element)} </>;
          })}
        </Form>
      </Modal>
      <Modal
        title={'新增' + `${TbaleToNameMap[tableKey]}`}
        visible={isItem}
        onOk={handleIsItemOk}
        onCancel={handleIsItemCancel}
        forceRender
      >
        <Form
          layout={'vertical'}
          form={addModalForm}
          onFinish={onEdit}
          // labelCol={{ span: 6 }}
          // wrapperCol={{ span: 14 }}
        >
          {DataList?.edit?.map((element: any, index: any) => {
            return <> {formItemBuilder(element)} </>;
          })}
        </Form>
      </Modal>
    </ConfigProvider>
  );
};

// export default TableBuileder;
export default connect(({ labmanagement, loading }: any) => ({
  ...labmanagement,
  dataLoad: loading.effects['labmanagement/dataSearch'],
}))(TableBuileder);
